from flask import Blueprint, request

from src.model import db
from src.model.UserModel import UserModel
from src.utils.response import Result

from src import siwa

# 创建蓝图
user = Blueprint("user", __name__)

from src.siwadoc.UserSiwa import UserBody, UserQuery, UserBodyId


# 新增用户
@user.route("/user", methods=["POST"])
@siwa.doc(tags=["用户管理"], summary="新增用户", description="新增用户记得把uid去掉，否则可能会导致重复uid异常",
          body=UserBody)
def add():
    user = request.json

    data = UserModel(**user)

    db.session.add(data)
    db.session.commit()

    return Result(200, "新增成功")


# 删除用户
@user.route("/user/<int:uid>", methods=["DELETE"])
@siwa.doc(tags=["用户管理"], summary="删除用户", description="通过ID删除指定用户")
def drop(uid):
    data = UserModel.query.filter_by(uid=uid).first()

    if not data:
        return Result(400, "删除失败：没有此用户")

    db.session.delete(data)
    db.session.commit()

    return Result(200, "删除用户成功")


# 批量删除
@user.route("/user", methods=["DELETE"])
@siwa.doc(tags=["用户管理"], summary="批量删除用户", description="[1,2,3] 删除ID为1、2、3的数据", body=UserBodyId)
def dropBatch():
    ids = request.json["ids"]

    for id in ids:
        data = UserModel.query.filter_by(uid=id).first()

        if not data:
            return Result(400, f"批量删除失败：没有ID：{id}的用户")

        db.session.delete(data)

    db.session.commit()

    return Result(200, "批量删除用户成功")


# 编辑用户
@user.route("/user", methods=["PATCH"])
@siwa.doc(tags=["用户管理"], summary="编辑用户", body=UserBody)
def edit():
    user = request.json

    data = UserModel.query.filter_by(uid=user["uid"]).update(user)

    if not data:
        return Result(400, "编辑失败：没有此用户")

    db.session.commit()

    return Result(200, "编辑成功")


# 获取用户详情
@user.route("/user/<int:uid>")
@siwa.doc(tags=["用户管理"], summary="获取用户详情", resp=UserBody)
def get(uid):
    data = UserModel.query.filter_by(uid=uid).first()

    if not data:
        return Result(400, "获取失败：没有此用户")

    return Result(200, "获取用户详情成功", data.to())


# 获取用户列表
@user.route("/user")
@siwa.doc(tags=["用户管理"], summary="获取用户列表", description="不传参数表示从第1页开始 每页查询5条数据",
          query=UserQuery)
def list():
    # 默认不传page或size, 则从第一页开始显示5条
    page = request.args.get("page", 1, type=int)
    size = request.args.get("size", 5, type=int)

    paginate = UserModel.query.paginate(page=page, per_page=size, error_out=False)

    data = {
        "result": [k.to() for k in paginate],
        "page": paginate.page,
        "size": paginate.per_page,
        "pages": paginate.pages,
        "total": paginate.total,
        "prev": paginate.has_prev,
        "next": paginate.has_next
    }

    return Result(200, "获取用户列表成功", data)
